import mysql from 'mysql2'


// 修改后的QueryResult接口
interface QueryResult<T = any> {
  results: T extends mysql.RowDataPacket[] ? T :
  T extends mysql.OkPacket ? [T] :
  any[]  // 最终回退到any[]确保兼容
  fields?: mysql.FieldPacket[]
}

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '12345678',
  database: process.env.DB_NAME || 'moten',
  port: parseInt(process.env.DB_PORT || '3306'),
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
})

const promisePool = pool.promise()

// 修改后的查询方法（添加类型断言）
export const query = async <T = any>(sql: string, values?: any[]): Promise<QueryResult<T>> => {
  const [result, fields] = await promisePool.query(sql, values)

  return {
    results: (Array.isArray(result) ? result : [result]) as T extends mysql.RowDataPacket[] ? T :
      T extends mysql.OkPacket ? [T] : any[],
    fields
  }
}

// 执行方法保持不变
export const execute = async (sql: string, values?: any[]): Promise<mysql.OkPacket> => {
  const [result] = await promisePool.query<mysql.OkPacket>(sql, values)
  return result
}

// 错误处理封装
export async function daoErrorHandler<T>(fn: () => Promise<T>): Promise<T> {
  try {
    return await fn()
  } catch (error: any) {
    console.error('Database error:', error)
    throw createError({
      statusCode: 500,
      message: 'Database operation failed',
      data: {
        code: error.code,
        sqlMessage: error.sqlMessage
      }
    })
  }
}

export default pool